﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;

namespace WebSimplicity.Data.Helpers
{
    public static class Config
    {
        public static string GetConnectionString()
        {
            return WebConfigurationManager.ConnectionStrings["WebSimplicityData"].ConnectionString;
        }
        public static EntityConnection GetConnection(string NameSpace)
        {
            string providerName = "System.Data.SqlClient";
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();
            entityBuilder.Provider = providerName;
            entityBuilder.ProviderConnectionString = GetConnectionString();
            entityBuilder.Metadata = string.Format(@"res://*/{0}.csdl|
                                       res://*/{0}.ssdl|
                                        res://*/{0}.msl", NameSpace);
            return new EntityConnection(entityBuilder.ToString());
        }

        public static void BuildConnectionString(string host, string db, string user, string pass)
        {
            SqlConnectionStringBuilder connstr =
                new SqlConnectionStringBuilder();
            connstr.DataSource = host;
            connstr.InitialCatalog = db;
            connstr.UserID = user;
            connstr.Password = pass;
            connstr.PersistSecurityInfo = true;
            ConnectionStringSettings connect = new ConnectionStringSettings("WebSimplicityData", connstr.ConnectionString, "System.Data.SqlClient");
            var cfg = WebConfigurationManager.OpenWebConfiguration(@"/");
            cfg.ConnectionStrings.ConnectionStrings.Clear();
            cfg.ConnectionStrings.ConnectionStrings.Add(connect);
            cfg.Save();
        }
        public static void AddApplicationSetting(string Key, string Value)
        {
            var cfg = WebConfigurationManager.OpenWebConfiguration(@"/");
            cfg.AppSettings.Settings.Add(Key, Value);
            cfg.Save();
        }
        public static string GetApplicationSetting(string Key)
        {
            return WebConfigurationManager.AppSettings[Key];
        }
    }
}
